#!/bin/bash
if [[ $(whoami) != "lfs" ]]; then
	echo "Please log in as user lfs...";
	exit 1;
fi
cd $LFS/sources/pkg || exit 1
source ./utils.sh || exit 2
#######################################
# set package name here
PACKAGE=$(echo $0 | sed -e 's/.*make_\(.*\).sh/\1/');
#######################################
PKG_NAME=$(pkgname tools $PACKAGE) || exit 1;
PKG_VERSION=$(pkgversion tools $PACKAGE) || exit 2;
PKG_ARCHIVE=$(pkgarchive tools $PACKAGE) || exit 3;
echo "make $PACKAGE ($PKG_NAME) with version $PKG_VERSION from archive $PKG_ARCHIVE"
./unpack.sh $PKG_ARCHIVE || exit 4;
cd ../$PKG_ARCHIVE || (errcho "Can not change into directory ../$PKG_ARCHIVE" && exit 5);
#######################################
# prepare package source (patch etc.)
if [ ! -r /usr/include/rpc/types.h ]; then
  su -c 'mkdir -pv /usr/include/rpc && cp -fv sunrpc/rpc/*.h /usr/include/rpc';
fi && \
rm -Rfv ../glibc-build && \
mkdir -v ../glibc-build && \
cd ../glibc-build



#######################################
ERR=$?;
if (($ERR != 0)); then
    errcho "Aborted package preparing with code $ERR";
    exit 6;
fi
#######################################
# configure and make package
CONFIG_GUESS=$(../$PKG_ARCHIVE/scripts/config.guess) && \
echo "config.guess result: $CONFIG_GUESS" && \
../$PKG_ARCHIVE/configure                             \
      --prefix=/tools                               \
      --host=$LFS_TGT                               \
      --build=$CONFIG_GUESS                          \
      --disable-profile                             \
      --enable-kernel=2.6.32                        \
      --with-headers=/tools/include                 \
      libc_cv_forced_unwind=yes                     \
      libc_cv_ctors_header=yes                      \
      libc_cv_c_cleanup=yes \
    && \
    make && \
    make install



#######################################
ERR=$?;
if (($ERR != 0)); then
    errcho "Aborted package building with code $ERR";
    exit 6;
fi
#######################################
# make post checks and configuration
echo 'main(){}' > dummy.c && \
$LFS_TGT-gcc dummy.c && \
ELF=$(readelf -l a.out | grep ': /tools') && \
if [[ $ELF == "" ]]; then
    errcho "Wrong linker path... $(readelf -l a.out | grep 'interpreter')";
    exit 10;
else
    echo "readelf result: $ELF";
fi && \
rm -v dummy.c a.out && \
cd .. && rm -Rfv glibc-build


#######################################
ERR=$?;
if (($ERR != 0)); then
    errcho "Aborted package building with code $ERR";
    exit 7;
fi
cd $LFS/sources && \
rm -Rfv $PKG_ARCHIVE || (errcho "Can not remove directory $PKG_ARCHIVE" && exit 8);
echo "Installed $PACKAGE"
echo " --OK--"
